import 'dart:async';
import 'dart:io';
import 'package:bruno/bruno.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:intl/intl.dart';
import 'package:native_dart_package/global.dart';
import 'package:native_dart_package/http/env/env_model.dart';
import 'package:native_dart_package/http/event_bus_instance/index.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:native_dart_package/store/sp_store.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:umeng_push_sdk/umeng_push_sdk.dart';
import 'package:xbr_gaode_amap/xbr_gaode_amap.dart';
import 'package:xbr_gaode_location/xbr_gaode_location.dart';
import 'package:yt_devops/routers/observer/auth_observer.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/patch_update_util.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/amap/map_const_config.dart';
import 'package:yt_devops/resources/str_res.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/routers/routers.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/styles/themes.dart';
import 'package:yt_devops/utils/constants/store_keys.dart';
import 'package:yt_devops/utils/update_dialog.dart';
import 'components/event_bus_util/eventbus_util.dart';
import 'components/log_utils.dart';
import 'components/network_image_load/image_utils.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'styles/bruno_themes.dart';
import 'utils/umeng/pusher.dart';

void main() {

  Global.init().then((value) {
    Log.init(isDebug: !kReleaseMode); //初始化日志打印
    Configs().loadConfigs().then((value) async {
      WidgetsFlutterBinding.ensureInitialized;
      HttpOverrides.global = MyHttpOverrides();
      await UserEntityManager().init();
      await GetStorage.init();

      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
      flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
          ?.requestNotificationsPermission();
      // _addCashCapture();
      registerPush();
      //地图初始化
      XbrGaodeAmap.initKey(
          androidKey: MapConstConfig.amapApiKeys.androidKey!,
          iosKey: MapConstConfig.amapApiKeys.iosKey!);
      XbrGaodeAmap.updatePrivacy(
          hasContains: true, hasShow: true, hasAgree: true);

      //定位初始化
      XbrGaodeLocation.initKey(
          androidKey: MapConstConfig.amapApiKeys.androidKey!,
          iosKey: MapConstConfig.amapApiKeys.iosKey!);
      XbrGaodeLocation.updatePrivacy(
          hasContains: true, hasShow: true, hasAgree: true);

      SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent, // 状态栏背景色
          statusBarBrightness: Brightness.light));
      EnviromentModel environment = await Configs().environment;
      ImageUtils.initialization(environment.api); //初始化网络图片工具
      runApp(const MyApp());
    });
  });
}

///添加错误抓取
_addCashCapture() async {
  // print('_addCashCapture=='+ Configs().environment.api.toString());
  // FlutterError.onError = (details) {
  //   FlutterError.presentError(details);
  //   MyErrorsHandler.widgetErrorDetails(details);
  // };
  // PlatformDispatcher.instance.onError = (error, stack) {
  //   MyErrorsHandler.platformError(error, stack);
  //   return true;
  // };
  // Isolate.current.addErrorListener(
  //   RawReceivePort((Function? handler) async {
  //     MyErrorsHandler.isolateError(handler);
  //   }).sendPort,
  // );
}

Future<void> registerPush() async {
  // await UmengCommonSdk.initCommon(
  //     "66a765ff79093f622220d13d", "665599058d52370b9d98787a", "AppStore", "");
  // UmengPushSdk.register("665599058d52370b9d98787a", "AppStore");
  if (Global.isLogin()) {
    // UmengHelper.agree().then((value) {
    //   UmengPusher.register();
    // });

    Log.d('setPushEnable===');
    await  UmengPusher.setLogEnable();
    await UmengPusher.setPushEnable();
     UmengPusher.setTokenCallback();
     UmengPusher.setMessageCallback();
     UmengPusher.setNotificationCallback();
  }
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp>
    with HttpUnthorizeListener, WidgetsBindingObserver {
  bool hasNewVersion = false;
  bool isForceUpdate = false; //是否强制升级
  DeviceServices services = Get.put(DeviceServices());

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addObserver(this);
    // subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    //   if (result == ConnectivityResult.mobile) {
    //     print('Connectivity===移动网络');
    //   } else if (result == ConnectivityResult.wifi) {
    //     print('Connectivity==Wifi');
    //   } else if (result == ConnectivityResult.none) {
    //     print('Connectivity===无网络');
    //   }
    // });
    EventBusUtil.getInstance().on<SplashScreenClose>().listen((event) {
      Log.d('SwitchLanguage===');
      // _showUpdate('lastVersion',isForceUpdate);
      _getAppVersion().then((value) async {
        if (!hasNewVersion) {
          Log.d('bool: version hasNewVersion $hasNewVersion');
          await UpdatePatchUtil().updatePatch();
          // UpdatePatchUtil().showRestartDialog(Get.context!);
        }
      });
    });
    if (Global.isLogin()) {
      _pushUmengToken();
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        Log.d("页面状态前台$state");
        if (Platform.isAndroid) {
          // Get.updateLocale(FuncUtils.getDefaultSystemLanguage());
        }
        break;
      case AppLifecycleState.paused:
        Log.d("页面状态后台$state");
        break;
      case AppLifecycleState.detached:
      // TODO: Handle this case.
      case AppLifecycleState.inactive:
      // TODO: Handle this case.
      case AppLifecycleState.hidden:
      // TODO: Handle this case.
    }
  }

  ///获取app版本
  Future _getAppVersion() async {
    // 判断是否登录,如果没有登录就不去提示更新,因为更新逻辑跟账号类型有关系
    if (UserEntityManager.instance.userModel.userId == null) {
      Log.d('用户未登录');
      return;
    }
    // platform是平台 0安卓 苹果1  appType是app类型 2代表E智慧能源app,1代表华辰
    var platform = '1';
    if (Platform.isAndroid) {
      platform = '0';
    }
    Log.d('用户已登录');
    var result =
    await services.getAppVersion({'platform': platform, 'appType': '2'});
    if (result != null &&
        result['current'] != null &&
        result['current']['version'] != null) {
      String version = result['current']['version'].toString();
      int versionCode = int.parse(version.replaceAll('.', ''));
      if (result['current']['isCoerce'] != null &&
          result['current']['isCoerce'].toString() == '1') {
        isForceUpdate = true;
      }
      await _checkUpdate(versionCode, version);
    }
  }

  //检查是否需要升级
  Future _checkUpdate(int serviceVersionCode, String lastVersion) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //获取当前的版本号
    int currentVersionCode = int.parse(packageInfo.version.replaceAll('.', ''));
    String saveDate = SpSotre.instance.getString(StoreKeys.saveDate) ?? '';
    //当前年月日
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('yyyy-MM-dd').format(now);
    //如果获取服务器的版本号比当前应用程序的版本号还高，且保存的日期不等于当前日期 那么提示升级(当天只提示一次), 否则检查是否有新的补丁包
    if (serviceVersionCode > currentVersionCode && formattedDate != saveDate) {
      SpSotre.instance.setString(StoreKeys.saveDate, formattedDate);
      hasNewVersion = true;
      _showUpdate(lastVersion, isForceUpdate);
    } else {}
    Log.d('_checkUpdate===');
  }

  _showUpdate(String version, bool isForceUpdate) {
    UpdateDialog.showUpdateDialog(
        Get.context!,
        '1.${ResKey.upgradeFixKnowBugs.tr} \n2.${ResKey.upgradeOptimizeUserExperience.tr}',
        version,
        isForceUpdate);
  }

  ///将友盟的token传给后台,后台需要定期去删除没有用的token
  _pushUmengToken() async {
    GetStorage storage = GetStorage();
    storage.write(StoreKeys.appIsInit, false);
    //当前年月日
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('yyyy-MM-dd').format(now);
    String saveDate = storage.read(StoreKeys.pushDeviceTokenDate) ?? '';
    if (formattedDate == saveDate) {
      return;
    }
    var platform = '1';
    if (Platform.isAndroid) {
      platform = '0';
    }

    String pushDeviceToken = storage.read(StoreKeys.pushDeviceToken) ?? '';
    if (pushDeviceToken.isNotEmpty) {
      var result = await services
          .saveToken({'platform': platform, 'deviceToken': pushDeviceToken});
      if (result != null) {
        storage.write(StoreKeys.pushDeviceTokenDate, formattedDate);
      }
      Log.d('result===$result');
    }
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
        minTextAdapt: true,
        designSize: const Size(375, 812),
        builder: (_, child) {
          BrunoThemes.register();
          return GetMaterialApp(
            title: ResKey.company.tr,
            locale: Configs.enviromentModel.locale ??
                FuncUtils.getDefaultSystemLanguage(),
            fallbackLocale: const Locale('zh', 'CN'), //备用语言
            translations: StringRes(),
            navigatorObservers: [AuthObserver()],
            // onReady:(){
            //   print('当前系统语言环境:111');
            // } ,
            // localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
            //   print('当前系统语言环境:$locale');
            //   print('当前系统语言环境:$supportedLocales');
            //   if(Platform.isAndroid){
            //     // Get.updateLocale(FuncUtils.getDefaultSystemLanguage());
            //   }
            //   return;
            // },
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
                scaffoldBackgroundColor: Colour.backgroundColor,
                primaryColor: Colour.primaryColor,
                textTheme: Themes.texThemeStyle,
                inputDecorationTheme: Themes.inputDecorationTheme,
                appBarTheme: Themes.appBarTheme,
                dividerColor: Colors.transparent,
                useMaterial3: false,
                fontFamilyFallback: const [
                  "PingFang SC",
                ]),
            localizationsDelegates: [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              BrnLocalizationDelegate.delegate,
            ],
            supportedLocales: const [
              Locale('en', 'US'),
              Locale('zh', 'CN'),
            ],
            getPages: Routers.routers,
            initialRoute: RouterPath.splash,
            unknownRoute: Routers.unknownRouter,
            builder: EasyLoading.init(
                builder: (BuildContext context, Widget? child) {
                  //点击空白区域隐藏键盘,并使其失去焦点
                  return MediaQuery(
                    data: MediaQuery.of(context)
                        .copyWith(textScaler: const TextScaler.linear(1.0)),
                    child: GestureDetector(
                      onTap: () {
                        FocusScopeNode currentFocus = FocusScope.of(context);
                        if (!currentFocus.hasPrimaryFocus &&
                            currentFocus.focusedChild != null) {
                          FocusManager.instance.primaryFocus?.unfocus();
                        }
                      },
                      child: child,
                    ),
                  );
                }),
          );
        });
  }
}

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

mixin HttpUnthorizeListener on State<MyApp> {
  StreamSubscription? stream;

  @override
  void initState() {
    super.initState();

    ///Stream演示event bus
    stream = eventBus.on<ApiException>().listen((event) {
      errorHandleFunction(event);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (stream != null) {
      stream!.cancel();
      stream = null;
    }
  }

  ///网络错误提醒
  errorHandleFunction(ApiException exception) {
    if (exception is UnauthorisedException) {
      if (Get.routing.current != RouterPath.login) {
        showError(exception.message);
        Get.offAllNamed(RouterPath.login);
      }
    }
  }
}
